import sys
from PyQt5.QtWidgets import (
    QWidget,
    QTableWidget,
    QVBoxLayout,
    QHBoxLayout,
    QDateTimeEdit,
    QApplication,
    QPushButton,
    QTableWidgetItem,
    QComboBox,
)
from .clientAPI import ClientAPI


class DataView(QWidget):
    def __init__(self, api: ClientAPI, parent=None):
        super().__init__(parent)
        self.api = api
        self.tags = []
        self.InitUI()

    def InitUI(self):
        self.setWindowTitle("Data View")
        vbox = QVBoxLayout()

        hbox = QHBoxLayout()
        self.startTimeEdit = QDateTimeEdit()
        self.startTimeEdit.setDisplayFormat("yyyy-MM-dd HH:mm")
        self.endTimeEdit = QDateTimeEdit()
        self.endTimeEdit.setDisplayFormat("yyyy-MM-dd HH:mm")
        self.searchButton = QPushButton("Search")
        self.searchButton.clicked.connect(self.SearchData)
        hbox.addWidget(self.startTimeEdit)
        hbox.addWidget(self.endTimeEdit)
        hbox.addWidget(self.searchButton)

        self.tagsCombo = QComboBox()
        self.table = QTableWidget()
        vbox.addLayout(hbox)
        vbox.addWidget(self.tagsCombo)
        vbox.addWidget(self.table)
        self.setLayout(vbox)
        self.show()

    def UpdateTags(self):
        self.tags = self.api.GetTags()
        self.tagsCombo.clear()
        self.tagsCombo.addItems(self.tags)

    def SearchData(self):
        start = self.startTimeEdit.dateTime().toPyDateTime()
        end = self.endTimeEdit.dateTime().toPyDateTime()
        frames = self.api.GetFrames(self.tagsCombo.currentText(), start, end, "post")
        if frames:
            height = len(frames)
            titles = frames[0].GetTitles()
            width = len(titles)

            self.table.setRowCount(height)
            self.table.setColumnCount(width)
            self.table.setHorizontalHeaderLabels(titles)
            self.table.setVerticalHeaderLabels([str(i) for i in range(height)])

            for i in range(height):
                values = frames[i].ConvertToList()
                for j in range(width):
                    self.table.setItem(i, j, QTableWidgetItem(str(values[j])))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DataView()
    sys.exit(app.exec_())
